package com.maruti.otterapi.trackbacks;

import com.maruti.otterapi.ListParameters;
import com.maruti.otterapi.Otter4JavaException;
import com.maruti.otterapi.TopsyConfig;
import com.maruti.otterapi.TopsyConstants;
import com.maruti.otterapi.TopsyInvoker;

public class Trackbacks {

	private TopsyConfig topsyConfig;

	public TopsyConfig getTopsyConfig() {
		return topsyConfig;
	}

	public void setTopsyConfig(TopsyConfig topsyConfig) {
		this.topsyConfig = topsyConfig;
	}

	/**
	 * @param criteria
	 * @return
	 * @throws Otter4JavaException
	 */
	public TrackbacksResponse trackbacks(TrackbackRequest request)
			throws Otter4JavaException {

		if (request.getListParams() == null
				|| request.getListParams().getPage() == null)
			return fetchAll(request);
		return fetch(request);
	}

	private TrackbacksResponse fetchAll(TrackbackRequest request)
			throws Otter4JavaException {

		int page = 1;
		ListParameters listParameters = null;
		if (request.getListParams() != null)
			listParameters = request.getListParams();
		else
			listParameters = new ListParameters();
		listParameters.setPage("" + page);
		listParameters.setPerpage("100");
		request.setListParams(listParameters);
		TrackbacksResponse response = fetch(request);
		int total = Integer.parseInt(response.getResponse().getTotal());
		int fetchedRecs = response.getResponse().getList().size();
		TrackbacksResponse response1 = null;
		String lastOffset = response.getResponse().getLast_offset();
		System.out.println(response.getResponse().getList().get(1).getContent());
		page++;
		while (total > fetchedRecs && page <= 10) {
			listParameters.setPage("" + page);
			listParameters.setOffset(lastOffset);
			response1 = fetch(request);
			System.out.println(response1.getResponse().getList().get(1).getContent());
			response.getResponse().getList().addAll(
					response1.getResponse().getList());
			fetchedRecs += response1.getResponse().getList().size();
			System.out.println(response1.getResponse().getList().size());
			lastOffset = response1.getResponse().getLast_offset();
			page++;
		}

		return response;
	}

	private TrackbacksResponse fetch(TrackbackRequest request)
			throws Otter4JavaException {
		TopsyInvoker invoker = new TopsyInvoker();
		invoker.setTopsyConfig(topsyConfig);

		String query = request.toQuery();

		TrackbacksResponse data = (TrackbacksResponse) invoker.fetchData(
				TopsyConstants.trackbacksURL + query, "trackbacks");

		return data;
	}

}
